package com.onion.search.es;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.apache.commons.lang3.StringUtils;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class JestClientUtils {

    private static JestClientFactory jestClientFactory;
    private static JestClient jestClient;

    private static final String ES_SERVER_ADDRESS = "es.server.address";
    private static final String ES_USERNAME = "es.username";
    private static final String ES_PASSWORD = "es.password";

    public void initConfig(){
        this.initConfig(null);
    }

    /**
     * 初始化ElasticSearch配置信息
     * @param properties
     */
    public void initConfig(Properties properties){
        if(jestClientFactory != null){
            return;
        }
        String esServerAddr = properties.getProperty(ES_SERVER_ADDRESS);
        if(StringUtils.isBlank(esServerAddr)){
            throw new RuntimeException("Not Found the config of " + ES_SERVER_ADDRESS);
        }
        String username = properties.getProperty(ES_USERNAME);
        String password = properties.getProperty(ES_PASSWORD);
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(esServerAddr);
        if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){
            builder.defaultCredentials(username, password);
        }
        jestClientFactory = new JestClientFactory();
        jestClientFactory.setHttpClientConfig(builder.connTimeout(60_000).readTimeout(60_000)
                                                     .maxConnectionIdleTime(600, TimeUnit.SECONDS)
                                                     .multiThreaded(true).build());
        jestClient = jestClientFactory.getObject();
    }

    /**
     * 获取JestClient
     * @return
     */
    public static JestClient getJestClient() {
        if(jestClient == null){
            synchronized (JestClientUtils.class){
                if(jestClient == null){
                    new JestClientUtils().initConfig();
                }
                if(jestClient == null){
                    throw new RuntimeException("JestClientUtils初始化出错!");
                }
            }
        }
        return jestClient;
    }

}